﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.VisualBasic;
using Org.BouncyCastle.Utilities;

namespace FanjiaHotelPlatform.utils.Kits
{
    /// <summary>
    ///  字符串工具类
    /// </summary>
    public static class StringKit
    {
        #region GetByteLength 返回字符串字节数
        /// <summary>
        ///  返回字符串字节数（1个汉字占2个字节）
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <returns>占用字节数</returns>
        public static int GetByteLength(string targetString)
        {
            return Encoding.Default.GetBytes(targetString).Length;
        }
        #endregion

        #region GetIndexInArray 返回字符串在指定字符串数组中的位置
        /// <summary>
        ///  返回字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="targetArray">目标数组</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns>字符串所处位置</returns>
        public static int GetIndexInArray(string targetString, string[] targetArray, bool ignoreCase)
        {
            for (int i = 0; i < targetArray.Length; i++)
            {
                if (ignoreCase)
                {
                    if (targetString.ToLower() == targetArray[i].ToLower())
                    {
                        return i;
                    }
                }
                else if (targetString == targetArray[i])
                {
                    return i;
                }
            }
            return -1;
        }
        #endregion

        #region IsInArray 判断字符串是否在指定字符串数组内
        /// <summary>
        ///  判断字符串是否在指定字符串数组内
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="targetArray">目标数组</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static bool IsInArray(string targetString, string[] targetArray, bool ignoreCase)
        {
            return GetIndexInArray(targetString, targetArray, ignoreCase) >= 0;
        }
        #endregion

        #region Trim 清除字符串中的回车/换行/空格
        /// <summary>
        ///  清除字符串中的回车/换行/空格
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <returns>处理后的新字符串</returns>
        public static string Trim(string targetString)
        {
            for (int i = targetString.Length; i >= 0; i--)
            {
                if (targetString[i].Equals(" ") || targetString[i].Equals("\r") || targetString[i].Equals("\n"))
                {
                    targetString.Remove(i, 1);
                }
            }
            return targetString;
        }

        /// <summary>
        /// 正则清除所有空格
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string TrimSpace(string input)
        {
            return Regex.Replace(input, @"\s", string.Empty);
        }
        #endregion

        #region ClearBr 清除字符串中的回车/换行
        /// <summary>
        ///  清除字符串中的回车/换行
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <returns>处理后的新字符串</returns>
        public static string ClearBr(string targetString)
        {
            Regex regex = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
            for (Match match = regex.Match(targetString); match.Success; match = match.NextMatch())
            {
                targetString = targetString.Replace(match.Groups[0].ToString(), "");
            }
            return targetString;
        }
        #endregion

        #region CutString 从字符串的指定位置截取指定长度
        /// <summary>
        ///  从字符串的指定位置截取指定长度
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="startIndex">开始截取位置</param>
        /// <param name="length">截取长度</param>
        /// <returns>截取出的新字符串</returns>
        public static string CutString(string targetString, int startIndex, int length)
        {
            try
            {
                if (startIndex >= 0)
                {
                    if (length < 0)
                    {
                        length = length * -1;
                        if (startIndex - length < 0)
                        {
                            length = startIndex;
                            startIndex = 0;
                        }
                        else
                        {
                            startIndex = startIndex - length;
                        }
                    }
                    if (startIndex > targetString.Length)
                    {
                        return string.Empty;
                    }
                }
                else
                {
                    if (length < 0)
                    {
                        return string.Empty;
                    }
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
                if (targetString.Length - startIndex < length)
                {
                    length = targetString.Length - startIndex;
                }
                return targetString.Substring(startIndex, length);
            }
            catch (Exception)
            {
                return targetString;
                throw;
            }

        }
        #endregion

        #region CutString 从字符串的指定位置开始截取到字符串尾部
        /// <summary>
        ///  从字符串的指定位置开始截取到字符串尾部
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="startIndex">开始截取位置</param>
        /// <returns>截取出的新字符串</returns>
        public static string CutString(string targetString, int startIndex)
        {
            return CutString(targetString, startIndex, targetString.Length);
        }
        #endregion

        #region CutString 从字符串的指定位置截取指定长度（字符串如果操过指定长度则将超出的部分用指定字符串代替）
        /// <summary>
        /// 截取指定长度的字符串（字符串如果操过指定长度则将超出的部分用指定字符串代替）
        /// </summary>
        /// <param name="targetString">要检查的字符串</param>
        /// <param name="startIndex">起始位置</param>
        /// <param name="length">指定长度</param>
        /// <param name="newString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string CutString(string targetString, int startIndex, int length, string newString)
        {
            if (targetString == null) return string.Empty;

            string resultString = targetString;
            if (length >= 0)
            {
                byte[] defaultBytes = Encoding.Default.GetBytes(targetString);
                //当字符串长度大于起始位置
                int endIndex = defaultBytes.Length;
                if (defaultBytes.Length > startIndex)
                {
                    //当要截取的长度在字符串的有效长度范围内
                    if (defaultBytes.Length > (startIndex + length))
                    {
                        endIndex = length + startIndex;
                    }
                    else
                    {
                        //当不在有效范围内时,只取到字符串的结尾
                        length = defaultBytes.Length - startIndex;
                        newString = string.Empty;
                    }
                    int realLength = length;
                    var resultFlag = new int[length];
                    int flag = 0;
                    for (int i = startIndex; i < endIndex; i++)
                    {
                        if (defaultBytes[i] > 127)
                        {
                            flag++;
                            if (flag == 3)
                            {
                                flag = 1;
                            }
                        }
                        else
                        {
                            flag = 0;
                        }
                        resultFlag[i] = flag;
                    }
                    if ((defaultBytes[endIndex - 1] > 127) && (resultFlag[length - 1] == 1))
                    {
                        realLength = length + 1;
                    }
                    byte[] resultBytes = new byte[realLength];
                    Array.Copy(defaultBytes, startIndex, resultBytes, 0, realLength);
                    resultString = Encoding.Default.GetString(resultBytes);
                    resultString = resultString + newString;
                }
            }
            return resultString;
        }

        #endregion

        #region CutString 从字符串的指定位置开始截取到字符串尾部 （字符串如果操过指定长度则将超出的部分用指定字符串代替）
        /// <summary>
        /// 从字符串的指定位置开始截取到字符串尾部（字符串如果操过指定长度则将超出的部分用指定字符串代替）
        /// </summary>
        /// <param name="targetString">要检查的字符串</param>
        /// <param name="length">指定长度</param>
        /// <param name="newString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string CutString(string targetString, int length, string newString)
        {
            return CutString(targetString, 0, length, newString);
        }
        #endregion

        #region Split 分割字符串
        /// <summary>
        ///  分割字符串
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="separator">分割符</param>
        /// <returns></returns>
        public static string[] Split(string targetString, string separator)
        {
            if (!string.IsNullOrEmpty(targetString))
            {
                if (targetString.IndexOf(separator) < 0)
                {
                    return new[] { targetString };
                }
                return Regex.Split(targetString, Regex.Escape(separator), RegexOptions.IgnoreCase);
            }
            return new string[0];
        }
        #endregion

        #region Split 分割字符串
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="separator">分割符</param>
        /// <param name="count">返回数组长度</param>
        /// <returns></returns>
        public static string[] Split(string targetString, string separator, int count)
        {
            string[] resultArray = new string[count];
            string[] splitedArray = Split(targetString, separator);
            for (int i = 0; i < count; i++)
            {
                if (i < splitedArray.Length)
                {
                    resultArray[i] = splitedArray[i];
                }
                else
                {
                    resultArray[i] = string.Empty;
                }
            }
            return resultArray;
        }
        #endregion

        #region Split 分割字符串
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="targetString">被分割的字符串</param>
        /// <param name="separator">分割符</param>
        /// <param name="ignoreRepeat">忽略重复项</param>
        /// <param name="maxItemLength">单个元素最大长度</param>
        /// <returns></returns>
        public static string[] Split(string targetString, string separator, bool ignoreRepeat, int maxItemLength)
        {
            string[] result = Split(targetString, separator);
            return ignoreRepeat ? DistinctArray(result, maxItemLength) : result;
        }
        #endregion

        #region Split 分割字符串
        /// <summary>
        ///  分割字符串
        /// </summary>
        /// <param name="targetString">被分割的字符串</param>
        /// <param name="separator">分割符</param>
        /// <param name="ignoreRepeat">忽略重复项</param>
        /// <param name="minItemLength">单个元素最小长度</param>
        /// <param name="maxItemLength">单个元素最大长度</param>
        /// <returns></returns>
        public static string[] Split(string targetString, string separator, bool ignoreRepeat, int minItemLength, int maxItemLength)
        {
            string[] resultArray = Split(targetString, separator);

            if (ignoreRepeat)
            {
                resultArray = DistinctArray(resultArray);
            }
            return PadArray(resultArray, minItemLength, maxItemLength);
        }
        #endregion

        #region Split 分割字符串
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="targetString">被分割的字符串</param>
        /// <param name="separator">分割符</param>
        /// <param name="ignoreRepeat">忽略重复项</param>
        /// <returns></returns>
        public static string[] Split(string targetString, string separator, bool ignoreRepeat)
        {
            return Split(targetString, separator, ignoreRepeat, 0);
        }
        #endregion

        #region Merge 合并字符串
        /// <summary>
        /// 合并字符串
        /// </summary>
        /// <param name="source">要合并的源字符串</param>
        /// <param name="target">要被合并到的目的字符串</param>
        /// <returns>合并到的目的字符串</returns>
        public static string Merge(string source, string target)
        {
            return Merge(source, target, string.Empty);
        }
        #endregion

        #region Merge 合并字符串
        /// <summary>
        /// 合并字符串
        /// </summary>
        /// <param name="source">要合并的源字符串</param>
        /// <param name="target">要被合并到的目的字符串</param>
        /// <param name="mergeChar">合并符</param>
        /// <returns>并到字符串</returns>
        public static string Merge(string source, string target, string mergeChar)
        {
            if (string.IsNullOrEmpty(target))
            {
                target = source;
            }
            else
            {
                target += mergeChar + source;
            }
            return target;
        }
        #endregion

        #region RemoveLastChar 删除最后一个字符
        /// <summary>
        /// 删除最后一个字符
        /// </summary>
        /// <param name="targetString"></param>
        /// <returns></returns>
        public static string RemoveLastChar(string targetString)
        {
            return (targetString == string.Empty) ? string.Empty : targetString.Substring(0, targetString.Length - 1);
        }
        #endregion

        #region PadArray 过滤字符串数组中每个元素为合适的大小
        /// <summary>
        /// 过滤字符串数组中每个元素为合适的大小
        /// 当长度小于minLength时，删除掉，-1为不限制最小长度
        /// 当长度大于maxLength时，取其前maxLength位
        /// 如果数组中有null元素，会被忽略掉
        /// </summary>
        /// <param name="targetArray">目标数组</param>
        /// <param name="minLength">单个元素最小长度</param>
        /// <param name="maxLength">单个元素最大长度</param>
        /// <returns></returns>
        public static string[] PadArray(string[] targetArray, int minLength, int maxLength)
        {
            if (minLength > maxLength)
            {
                int length = maxLength;
                maxLength = minLength;
                minLength = length;
            }

            int miniStringCount = 0;

            for (int i = 0; i < targetArray.Length; i++)
            {
                if (minLength > -1 && targetArray[i].Length < minLength)
                {
                    targetArray[i] = null;
                    continue;
                }
                if (targetArray[i].Length > maxLength)
                {
                    targetArray[i] = targetArray[i].Substring(0, maxLength);
                }
                miniStringCount++;
            }

            string[] resultArray = new string[miniStringCount];

            for (int i = 0, j = 0; i < targetArray.Length && j < resultArray.Length; i++)
            {
                if (!string.IsNullOrEmpty(targetArray[i]))
                {
                    resultArray[j] = targetArray[i];
                    j++;
                }
            }
            return resultArray;
        }
        #endregion

        #region DistinctArray 清除字符串数组中的重复项
        /// <summary>
        /// 清除字符串数组中的重复项
        /// </summary>
        /// <param name="targetArray">字符串数组</param>
        /// <param name="maxItemLength">字符串数组中单个元素的最大长度</param>
        /// <returns></returns>
        public static string[] DistinctArray(string[] targetArray, int maxItemLength)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach (string @string in targetArray)
            {
                string key = @string;
                if (maxItemLength > 0 && key.Length > maxItemLength)
                {
                    key = key.Substring(0, maxItemLength);
                }
                dictionary[key.Trim()] = @string;
            }
            string[] resultArray = new string[dictionary.Count];
            dictionary.Keys.CopyTo(resultArray, 0);
            return resultArray;
        }
        #endregion

        #region DistinctArray 清除字符串数组中的重复项
        /// <summary>
        /// 清除字符串数组中的重复项
        /// </summary>
        /// <param name="targetArray">字符串数组</param>
        /// <returns></returns>
        public static string[] DistinctArray(string[] targetArray)
        {
            return DistinctArray(targetArray, 0);
        }
        #endregion

        #region FilterIllegal 过滤非法字符（替换非法字符）
        /// <summary>
        /// 过滤非法字符（替换非法字符）
        /// </summary>
        /// <param name="targetString">目标字符串</param>
        /// <param name="illegalString">非法字符集（oldValue=newValue\r\n格式）</param>
        /// <returns></returns>
        public static string FilterIllegal(string targetString, string illegalString)
        {
            string[] illegalArray = Split(illegalString, "\r\n");
            foreach (string illegal in illegalArray)
            {
                string oldValue = illegal.Substring(0, illegal.IndexOf("="));
                string newValue = illegal.Substring(illegal.IndexOf("=") + 1);
                targetString = targetString.Replace(oldValue, newValue);
            }
            return targetString;
        }
        #endregion

        #region SbcCaseToNumberic 将全角数字转换为数字
        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="targetString"></param>
        /// <returns></returns>
        public static string SbcCaseToNumberic(string targetString)
        {
            char[] @char = targetString.ToCharArray();
            for (int i = 0; i < @char.Length; i++)
            {
                byte[] bytes = Encoding.Unicode.GetBytes(@char, i, 1);
                if (bytes.Length == 2)
                {
                    if (bytes[1] == 255)
                    {
                        bytes[0] = (byte)(bytes[0] + 32);
                        bytes[1] = 0;
                        @char[i] = Encoding.Unicode.GetChars(bytes)[0];
                    }
                }
            }
            return new string(@char);
        }
        #endregion

        #region 添加时字符处理
        public static string StrAdd(string str)
        {
            str = str.Replace("'", " ’");
            str = str.Replace("\"", "&quot;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\n", "<br>");

            return str;
        }
        #endregion

        #region 修改textbox显示
        public static string StrTextBox(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace(" ’", "'");
                str = str.Replace("&quot;", "\"");
                str = str.Replace("&nbsp;", " ");
                str = str.Replace("&lt;", "<");
                str = str.Replace("&gt;", ">");
                str = str.Replace("<br>", "\n");

                return str;
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 显示时字符处理
        public static string StrView(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace(" ’", "'");
                str = str.Replace("&quot;", "\"");
                str = str.Replace("&nbsp;", " ");
                str = str.Replace("&lt;", "<");
                str = str.Replace("&gt;", ">");
                return str;
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 操作提示
        public static void StringJs(string strname, string strurl)
        {
            string strvalue = "<script language='javascript'>alert('" + strname + "');location='" + strurl + "';</script>";
            HttpContext.Current.Response.Write(strvalue);
        }
        public static void StringJs(string strname)
        {
            string strvalue = "<script language='javascript'>alert('" + strname + "');</script>";
            HttpContext.Current.Response.Write(strvalue);
        }
        #endregion

        #region 过滤字符串中的注入跨站脚本
        ///<summary>
        /// 过滤字符串中的注入跨站脚本(先进行UrlDecode再过滤脚本关键字)
        /// 过滤脚本如:<script>window.alert("test");</script>输出window.alert("test");
        /// 如<a href = "javascript:onclick='fun1();'">输出<a href=" onXXX='fun1();'">
        /// 过滤掉javascript和 onXXX
        ///</summary>
        ///<param name="source">需要过滤的字符串</param>
        ///<returns>过滤后的字符串</returns>
        public static string XSSFilter(string source)
        {
            if (source == "") return source;

            string result = HttpUtility.UrlDecode(source);

            string replaceEventStr = " onXXX =";
            string tmpStr = "";

            string patternGeneral = @"<[^<>]*>";                              //例如 <abcd>
            string patternEvent = @"([\s]|[:])+[o]{1}[n]{1}\w*\s*={1}";     // 空白字符或: on事件=
            string patternScriptBegin = @"\s*((javascript)|(vbscript))\s*[:]?";  // javascript或vbscript:
            string patternScriptEnd = @"<([\s/])*script.*>";                       // </script>   
            string patternTag = @"<([\s/])*\S.+>";                       // 例如</textarea>

            Regex regexGeneral = new Regex(patternGeneral, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regexEvent = new Regex(patternEvent, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regexScriptEnd = new Regex(patternScriptEnd, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regexScriptBegin = new Regex(patternScriptBegin, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regexTag = new Regex(patternTag, RegexOptions.Compiled | RegexOptions.IgnoreCase);


            Match matchGeneral, matchEvent, matchScriptEnd, matchScriptBegin, matchTag;

            //符合类似 <abcd> 条件的
            #region 符合类似 <abcd> 条件的
            //过滤字符串中的 </script>   
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchScriptEnd = regexScriptEnd.Match(tmpStr);
                if (matchScriptEnd.Success)
                {
                    tmpStr = regexScriptEnd.Replace(tmpStr, "");
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            //过滤字符串中的脚本事件
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchEvent = regexEvent.Match(tmpStr);
                if (matchEvent.Success)
                {
                    tmpStr = regexEvent.Replace(tmpStr, replaceEventStr);
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            //过滤字符串中的 javascript或vbscript:
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchScriptBegin = regexScriptBegin.Match(tmpStr);
                if (matchScriptBegin.Success)
                {
                    tmpStr = regexScriptBegin.Replace(tmpStr, "");
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            #endregion

            //过滤字符串中的事件 例如 onclick --> onXXX
            for (matchEvent = regexEvent.Match(result); matchEvent.Success; matchEvent = matchEvent.NextMatch())
            {
                tmpStr = matchEvent.Groups[0].Value;
                tmpStr = regexEvent.Replace(tmpStr, replaceEventStr);
                result = result.Replace(matchEvent.Groups[0].Value, tmpStr);
            }

            //过滤掉html标签，类似</textarea>
            for (matchTag = regexTag.Match(result); matchTag.Success; matchTag = matchTag.NextMatch())
            {
                tmpStr = matchTag.Groups[0].Value;
                tmpStr = regexTag.Replace(tmpStr, "");
                result = result.Replace(matchTag.Groups[0].Value, tmpStr);
            }


            return result;
        }
        #endregion

        #region SQL注入
        ///<summary>
        /// 过滤字符串中注入SQL脚本的方法
        ///</summary>
        ///<param name="source">传入的字符串</param>
        ///<returns>过滤后的字符串</returns>
        public static string SqlFilters(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return "";
            }
            source = source.Trim();
            //半角括号替换为全角括号
            source = source.Replace("'", "").Replace(";", "").Replace("(", "（").Replace(")", "）");

            //去除执行SQL语句的命令关键字
            source = Regex.Replace(source, " select", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "insert", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "update", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "delete", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "drop", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "truncate", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "declare", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "/add", "", RegexOptions.IgnoreCase);

            source = Regex.Replace(source, "net user", "", RegexOptions.IgnoreCase);

            //去除执行存储过程的命令关键字 
            source = Regex.Replace(source, "exec", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "execute", "", RegexOptions.IgnoreCase);

            //去除系统存储过程或扩展存储过程关键字
            source = Regex.Replace(source, "xp_", "x p_", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "sp_", "s p_", RegexOptions.IgnoreCase);

            //防止16进制注入
            source = Regex.Replace(source, "0x", "0 x", RegexOptions.IgnoreCase);

            return source;
        }

        #endregion

        #region 判断字符是否存在字符串中
        /// <summary>
        /// 判断字符是否存在字符串中
        /// </summary>
        /// <param name="str">需要查找的字符串</param>
        /// <param name="strText">字符串内容</param>
        /// <returns></returns>
        public static bool IsInString(string str, string strText)
        {
            Regex r = new Regex(str); // 定义一个Regex对象实例
            Match m = r.Match(strText); // 在字符串中匹配
            if (m.Success)
            {
                return true;
            }
            return false;
        }

        #endregion

        #region 获取字符中存在某个元素的个数

        public static int GetStrSpCount(string strValue, char s)
        {
            string[] strArray = strValue.Split(s);
            int i = 0;
            foreach (string str in strArray)
            {
                if (str != "")
                {
                    i++;
                }
            }
            return i - 1;
        }
        #endregion

        #region 获取截取的数值

        public static string GetStrSpCup(string strValue, char s, int iNum)
        {
            string strReturn = "";
            string[] strArray = strValue.Split(s);
            int i = 0;
            foreach (string str in strArray)
            {
                if (str != "" && i < iNum)
                {
                    strReturn += str + "-";
                    i++;
                }
            }
            strReturn = strReturn.TrimEnd('-');
            return strReturn;
        }
        #endregion

        #region 判断是否存在SQL注入
        public static bool ProcessSqlStr(string str, out string strInfo)
        {
            strInfo = "";
            try
            {
                if (str.Trim() != "")
                {
                    str = str.ToLower().Replace("isdeleted", "");
                    //UpdateUser --->过滤update 
                    //Country ---> 不过滤count
                    string sqlStr = "exec|insert+|select+|delete|update |chr|mid|master+|truncate|char|declare|drop+|drop+table|creat+|create|*|iframe|script|";
                    sqlStr += "exec+|insert|delete+|update+|count(|count+|chr+|+mid(|+mid+|+master+|truncate+|char+|+char(|declare+|drop+table|creat+table|‘|;|；|";
                    string[] anySqlStr = sqlStr.Split('|');
                    foreach (string ss in anySqlStr)
                    {
                        if (ss != "" && str.ToLower().IndexOf(ss) != -1)
                        {
                            strInfo = ss;
                            return false;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                strInfo = exception.Message;
                return false;
            }
            return true;
        }
        #endregion

        #region 获取Request的值
        public static string GetRequestName(string strKeys)
        {
            string strValue = HttpContext.Current.Request[strKeys];
            //已加SQL注入过滤
            string strValues = HttpContext.Current.Server.UrlDecode(SqlFilters(strValue));
            return strValues;
        }
        #endregion

        #region 判断Request是否存在

        public static bool IsRequest(string strKeys)
        {
            return !string.IsNullOrEmpty(HttpContext.Current.Request[strKeys]);
        }

        #endregion

        #region 密码强度判断

        /// <summary>
        /// 密码强度
        /// </summary>
        public enum Strength
        {
            Invalid = 0, //无效密码
            Weak = 1, //低强度密码
            Normal = 2, //中强度密码
            Strong = 3 //高强度密码
        };
        /// <summary>
        /// 计算密码强度
        /// </summary>
        /// <param name="password">密码字符串</param>
        /// <returns></returns>
        public static Strength PasswordStrength(string password)
        {
            //空字符串强度值为0
            if (password == "") return Strength.Invalid;
            //字符统计
            int iNum = 0, iLtt = 0, iSym = 0;
            foreach (char c in password)
            {
                if (c >= '0' && c <= '9') iNum++;
                else if (c >= 'a' && c <= 'z') iLtt++;
                else if (c >= 'A' && c <= 'Z') iLtt++;
                else iSym++;
            }
            if (iLtt == 0 && iSym == 0) return Strength.Weak; //纯数字密码
            if (iNum == 0 && iLtt == 0) return Strength.Weak; //纯符号密码
            if (iNum == 0 && iSym == 0) return Strength.Weak; //纯字母密码
            if (password.Length < 6) return Strength.Weak; //长度不大于6的密码
            if (iLtt == 0) return Strength.Normal; //数字和符号构成的密码
            if (iSym == 0) return Strength.Normal; //数字和字母构成的密码
            if (iNum == 0) return Strength.Normal; //字母和符号构成的密码
            if (password.Length <= 10) return Strength.Normal; //长度不大于10的密码
            return Strength.Strong; //由数字、字母、符号构成的密码
        }

        /// <summary>
        /// 字符串写入文件
        /// </summary>
        /// <param name="logInfo">日志内容</param>
        public static void WriteLog(string logInfo)
        {
            string sMonth = DateTime.Now.ToString("MM");
            string sYear = DateTime.Now.ToString("yyyy");
            string sDay = DateTime.Now.ToString("dd");

            string sFileName = AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth + "/" + sDay +
                               DateTime.Now.ToString("yyyy-MM-ddHHmmssfff") + ".log";

            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/"))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/");
            }
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear);
            }
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth);
            }
            if (!File.Exists(sFileName))
            {
                File.Create(sFileName).Close();
            }

            //写日志
            System.IO.StreamWriter sw = new System.IO.StreamWriter(sFileName, true);
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "        "
                + logInfo);
            sw.Close();
        }

        #endregion

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="logInfo">内容</param>
        /// <param name="fileName"></param>
        public static void WriteInfoToFileNoRw(string logInfo, string fileName = "")
        {
            string sMonth = DateTime.Now.ToString("MM");
            string sYear = DateTime.Now.ToString("yyyy");
            string sDay = DateTime.Now.ToString("dd");

            string sFileName = string.Empty;

            if (!string.IsNullOrEmpty(fileName))
            {
                sFileName = AppDomain.CurrentDomain.BaseDirectory + "log/" + fileName + ".log";
            }
            else
            {
                sFileName = AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth + "/" + sDay + ".log";
                //DateTime.Now.ToString("yyyy-MM-ddHHmmssfff") + ".log";
            }

            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/"))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/");
            }
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear);
            }
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth);
            }
            if (!File.Exists(sFileName))
            {
                File.Create(sFileName).Close();
            }

            //写入文件
            System.IO.StreamWriter sw = new System.IO.StreamWriter(sFileName, true);
            sw.WriteLine(logInfo);
            sw.Close();
        }

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="logInfo">内容</param>
        /// <param name="fileName"></param>
        public static void WriteInfoToFile(string logInfo, string fileName = "")
        {
            string sMonth = DateTime.Now.ToString("MM");
            string sYear = DateTime.Now.ToString("yyyy");
            string sDay = DateTime.Now.ToString("dd");

            string sFileName = string.Empty;

            if (!string.IsNullOrEmpty(fileName))
            {
                sFileName = AppDomain.CurrentDomain.BaseDirectory + "log/" + fileName + ".log";
            }
            else
            {
                sFileName = AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth + "/" + sDay + ".log";
                //DateTime.Now.ToString("yyyy-MM-ddHHmmssfff") + ".log";
            }

            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/"))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/");
            }
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear);
            }
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log/" + sYear + "/" + sMonth);
            }
            if (!File.Exists(sFileName))
            {
                File.Create(sFileName).Close();
            }

            //写入文件
            System.IO.StreamWriter sw = new System.IO.StreamWriter(sFileName, false);
            sw.WriteLine(logInfo);
            sw.Close();
        }

        /// <summary>
        /// 获取指定路径文件内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string GetFileContent(string filePath)
        {
            string textStr = string.Empty;

            if (File.Exists(filePath))
            {
                //直接读取出字符串
                textStr = System.IO.File.ReadAllText(filePath);
            }

            return textStr;
        }
        public static readonly List<char> subStringBySplits = new List<char> { '(', '（', '-', '[', ']', ')', '）', '_' };
        /// <summary>
        /// 替换酒店名称中不合法的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SubStringByChars(string str)
        {

            var startIndex = str.Length;
            //var endIndex = -1;
            subStringBySplits.ForEach(m =>
            {
                var t = str.IndexOf(m);
                if (t < startIndex && t > -1)
                {
                    startIndex = t;
                }
            });
            /*
            subStringBySplits.ForEach(m => {
                var t = str.IndexOf(m);
                if (t > endIndex)
                {
                    endIndex = t;
                }
            });
            if(0< startIndex && endIndex<=str.Length&& startIndex<endIndex)
            {
                return str.Remove(startIndex,endIndex-startIndex+1);
            }
            else if(startIndex>0&& startIndex !=str.Length&& endIndex==-1)
            {
                return str.Remove(startIndex, str.Length - startIndex);
            }*/
            if (startIndex != str.Length && 0 < startIndex)
            {
                return str.Remove(startIndex, str.Length - startIndex);
            }
            return str;
        }
        /// <summary>
        /// 标准房替换
        /// </summary>
        /// <param name="roomName"></param>
        /// <returns></returns>
        public static string CorrectStandardRoomNameS1(string roomName)
        {
            var regex = new System.Text.RegularExpressions.Regex(ReplaceStandardRoomNameRegex1, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (regex.IsMatch(roomName))
            {
                var match = regex.Match(roomName);
                var groups = new List<string>(3);
                foreach (var g in match.Groups)
                {
                    if (string.IsNullOrWhiteSpace(g.ToString())) continue;
                    groups.Add(g.ToString());
                    if (groups.Count == 3)
                        break;
                }

                if (groups.Count == 2)
                {
                    groups.Add(string.Empty);
                }

                return string.Format("{0}双床房", groups[2]);
            }
            return roomName;
        }
        /// <summary>
        /// 标准房替换
        /// </summary>
        /// <param name="roomName"></param>
        /// <returns></returns>
        public static string CorrectStandardRoomNameS2(string roomName)
        {
            var regex = new System.Text.RegularExpressions.Regex(ReplaceStandardRoomNameRegex2, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return regex.IsMatch(roomName) ? "双床房" : roomName;
        }
        public static int CountStandardRoomNameS1Matchs(IEnumerable<string> roomNames)
        {
            var regex = new System.Text.RegularExpressions.Regex(ReplaceStandardRoomNameRegex1, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return roomNames.Count(m => regex.IsMatch(m));
        }
        public static int CountStandardRoomNameS2Matchs(IEnumerable<string> roomNames)
        {
            var regex = new System.Text.RegularExpressions.Regex(ReplaceStandardRoomNameRegex2, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return roomNames.Count(m => regex.IsMatch(m));
        }
        /// <summary>
        /// 房型名称 “间”替换为“房”
        /// </summary>
        /// <param name="roomName"></param>
        /// <returns></returns>
        public static string ReplaceStandardRoomName(string roomName)
        {
            return roomName.Replace("间", "房");
        }

        /// <summary>
        /// 标准房替换正则表达式维护
        /// </summary>
        private static string ReplaceStandardRoomNameRegex1
        {
            get
            {
                var regsub = "([^a-z^A-Z^0-9]+)";
                var groups = new List<string>
                {
                    "^{0}标准房$",
                    "^{0}标准间$",
                    "^{0}标(间|房)$",
                    "^标准{0}房$",
                    "^标准{0}间$",
                    "^{0}双床房$",
                    "^{0}双床间",
                };
                var reg = "(" + string.Join(")|(", groups.ToArray()) + ")";//最终，拼接为一个字符串：(...)|(...)

                return string.Format(reg, regsub);
            }
        }

        /// <summary>
        /// 标准房替换正则表达式维护
        /// </summary>
        private static string ReplaceStandardRoomNameRegex2
        {
            get
            {
                var groups = new List<string>
               {
                    "^标准房$",
                    "^标准间$",
                    "^标间$",
                    "^标准双床房$",
                    "^标准双床间$",
                    //"^标准双人间$",
                    "^双床房$",
                    "^双床间$",
               };
                var reg = "(" + string.Join(")|(", groups.ToArray()) + ")";//最终，拼接为一个字符串：(...)|(...)

                return reg;
            }
        }

        /// <summary>
        /// 标准化房型名称
        /// </summary>
        /// <param name="roomName">房型名称</param>
        /// <returns>标准化后的房型名称</returns>
        public static string NormalizeRoomName(string roomName)
        {
            roomName = roomName.ToUpper();
            roomName = SubStringByChars(roomName);
            roomName = ReplaceStandardRoomName(roomName);
            roomName = CorrectStandardRoomNameS1(roomName);
            roomName = CorrectStandardRoomNameS2(roomName);
            return roomName;
        }

        /// <summary>
        /// 用来处理房型名称中没有意义的字符
        /// </summary>
        /// <param name="roomAndPriceName">房型名称或者房型产品价格名称</param>
        /// <param name="isAgrePrice">是否协议价格</param>
        /// <returns></returns>
        public static string CorrectRoomAndPriceName(string roomAndPriceName, bool isAgrePrice = false)
        {
            if (isAgrePrice)
                return roomAndPriceName;

            //roomAndPriceName = Regex.Replace(roomAndPriceName, @"\s", "");
            roomAndPriceName = roomAndPriceName.ToUpper();
            roomAndPriceName = SubStringByChars(roomAndPriceName);
            roomAndPriceName = CorrectStandardRoomNameS1(roomAndPriceName);
            roomAndPriceName = CorrectStandardRoomNameS2(roomAndPriceName);
            return roomAndPriceName;
        }

        /// <summary>
        /// 图片是否替换成https
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ReplaceUrlToHttps(string url)
        {
            if (ConfigurationManager.AppSettings["IsImgReplaceHttps"] == "1")
            {
                if (url.ToLower().StartsWith("http://"))
                {
                    return string.Format("https://{0}", url.Substring(7));
                }
            }

            return url;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="maxPeople">最大人数</param>
        /// <returns></returns>
        public static string RoomMaxPeople(string maxPeople)
        {
            int _maxPeople = 0;
            if (!int.TryParse(maxPeople, out _maxPeople))
            {
                return "2";
            }
            else
            {
                if (_maxPeople > 3)
                {
                    return "3";
                }
                else if (_maxPeople <= 0)
                {
                    return "2";
                }
                else
                {
                    return maxPeople;
                }
            }
        }

        public static string GetScoreDesc(decimal score)
        {
            var scoreD = Convert.ToDouble(score);
            if (scoreD == 5.0)
            {
                return "超级棒";
            }
            else if (scoreD >= 4.5)
            {
                return "非常棒";
            }
            else if (scoreD >= 4.0)
            {
                return "棒棒的";
            }
            //else if (scoreD >= 3.5)
            //{
            //    return "不错哦";
            //}
            return "";
        }
    }
}
